package TwentyEighthDay;

import java.util.*;

public class CombinationSum2 {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if (candidates.length == 0){
            return res;
        }
        Arrays.sort(candidates);
        Deque<Integer> path = new ArrayDeque<>();
        backTracking(candidates, target, 0, path, res);
        return res;
    }

    private void backTracking(int[] candidates, int target, int index, Deque<Integer> path, List<List<Integer>> res) {
        if (target == 0){
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (target - candidates[i] < 0){
                break;
            }
            if (i > index && candidates[i] == candidates[i-1]){
                continue;
            }
            path.add(candidates[i]);
            backTracking(candidates, target - candidates[i], i+1, path, res);
            path.removeLast();
        }
    }

}
